package com.cskaoyan.mr.wordcount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/**
 * @ClassName WordCountReducer
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/2/13 11:02
 * @Version V1.0
 **/
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

    /**
     * 相同的key值，会调用一次reduce
     * @param key
     * @param values
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        //下面这段话的逻辑就是将values里面的数字进行相加
        int sum = 0;
        Iterator<IntWritable> iterator = values.iterator();
        while (iterator.hasNext()){
            IntWritable number = iterator.next();
            sum += number.get();
        }
        //再一并写出去
        context.write(key, new IntWritable(sum));
    }
}
